<template>
    <div class="boxContentCss">
        <el-form ref="form" :model="form" label-position="right" label-width="auto">
            <EdCreateCard :title="isUpdate ? '编辑商品' : '商品录入' ">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-row :gutter="20" class="mainBackgroundColor marginLeft0Right0 border-radius-bottom width-100">
                        <el-col :span="12" class="">
                            <el-form :model="form" ref="formRef" class="rowStyle" label-width="120px" size="small">
                                <el-form-item label="商品名称：" prop="productName" :rules="$validate.validates({required:true,msg:'商品名称不能为空'})">
                                    <el-input v-model="form.productName" style="max-width: 600px" placeholder="请输入商品名称" maxlength="20"></el-input>
                                </el-form-item>

                                <el-form-item label="商品来源：" prop="productSource" :rules="$validate.validates({required:true,msg:'商品来源不能为空'})">
                                    <el-select v-model="form.productSource" style="max-width: 600px" placeholder="请选择" class="width-100">
                                        <el-option
                                                v-for="item in sipSource"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="商品类别：" prop="categoryId" :rules="$validate.validates({required:true,msg:'商品类别不能为空'})">
                                    <EdCascader ref="CascaderRef" v-model="form.categoryId" :cascaderParams="cascaderParams" @change-emit-label="changeEmitLabel"></EdCascader>
                                </el-form-item>

                                <el-form-item label="商品价格：" prop="money" :rules="$validate.validates({required:true,msg:'商品价格不能为空'})">
                                    <el-input v-model="form.money" placeholder="请输入商品价格" maxlength="8" class="width100"></el-input><span class="color085 marginRight8 marginLeft8">元</span>
                                </el-form-item>
                                <el-form-item label="商品URL：" prop="productUrl" :rules="$validate.validates({required:true,msg:'商品URL不能为空'})">
                                    <el-input v-model="form.productUrl" style="max-width: 600px" placeholder="请输入商品URL"></el-input>
                                </el-form-item>
                                <el-form-item label="商品主图：" prop="pics" :rules="$validate.validates({required:true,msg:'商品主图不能为空'})">
                                    <el-upload
                                            class="business-uploader-single-313"
                                            accept=".jpeg,.png,.jpg"
                                            :action="action"
                                            :headers="headers"
                                            :show-file-list="false"
                                            :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                        <el-image v-if="form.pics.length > 0" :src="form.pics[0]" fit="contain"></el-image>
                                        <div v-else>
                                            <i class="el-icon-plus avatar-uploader-icon"></i>
                                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 0 0 8px 0;line-height: 1">上传图片</div>
                                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65);line-height: 1">大小不超过2M</div>
                                        </div>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item class="paddingBottom145 btnClass1">
                                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">保 存</el-button>
                                    <el-button class="ed-button ed_white_bottom" @click="reset()">重 置</el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>
                </div>
            </EdCreateCard>
        </el-form>
    </div>
</template>

<script>
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import {productOnupdate ,getAllCategory ,productOnsave ,productOndetail} from "src/api/shoppingMall";
    import {getDictByCode} from "src/api/dictionaries";
    import {getToken} from 'src/utils/auth'
    export default {
        name: "lineCreate",
        components:{
            EdCreateCard,
            EdCascader
        },
        data(){
            return{
                form:{
                    productName:"",
                    productUrl:"",
                    money:"",
                    categoryName:"",
                    categoryId:"",
                    productSource:"",
                    pics:[],
                },
                action:"",
                headers:{
                    RdAuthorization: getToken()
                },
                upFile:new FormData(),
                disabled:false,
                isUpdate:false,
                mobile:null,
                sipSource:[],
                categoryOptions:[],

                cascaderParams:{
                    placeholder:"商品类别",
                    props:{label:'categoryName',value:'id',emitPath:false},
                    options: []
                },
            }
        },
        mounted(){

            getDictByCode("commodity_source").then(response => {
                if(response.code == 20000) {
                    response.data.items.forEach((item)=>{
                        this.sipSource.push({
                            value:item.value,
                            label:item.label
                        })
                    })
                }
            })

            this.getAllCategory();
            this.action = this.$baseApi + "/file/upload";
            if(this.$route.query.id){
                this.isUpdate = true;
                this.productOndetail()
            }else {
                this.isUpdate = false;
            }
        },
        methods:{
            getAllCategory(){
                //实物商品
                getAllCategory({id:0}).then(response => {
                    if(response.code == 20000) {
                        this.cascaderParams.options = response.data
                    }
                })
            },
            productOndetail(){
                productOndetail({id:this.$route.query.id}).then(response => {
                    if(response.code == 20000) {
                        this.form = {
                            id:this.$route.query.id,
                            productName:response.data.productName,
                            productUrl:response.data.productUrl,
                            money:response.data.money,
                            categoryName:response.data.categoryName,
                            categoryId:response.data.categoryId,
                            productSource:response.data.productSource,
                            pics:response.data.pics,
                        };
                    }
                })
            },
            handleAvatarSuccess(file){
                this.$set(this.form,"pics",[file.data]);
                this.$refs.formRef.validateField("pics")
            },
            beforeAvatarUpload(file){
                const fileType = file.name.split('.');
                const fileDate = fileType.slice(-1);
                if (['jpeg', 'jpg', 'png'].indexOf(fileDate[0]) < 0) {
                    this.$message.error('仅支持格式：.jpeg、.jpg、.png!');
                    return false
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 2MB!');
                }
                return isLt2M;
            },
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.disabled = true;
                        let urlFn;
                        if(this.isUpdate){
                            urlFn = productOnupdate;
                        }else {
                            urlFn = productOnsave;
                        }
                        urlFn(this.form).then(response => {
                            if(response.code == 20000) {
                                this.disabled = false;
                                this.$message.success({
                                    message: '保存成功',
                                    center: true,
                                    duration: 2000,
                                })
                                window.setTimeout(() => {
                                    this.$utilsSet.goBack(this.$router);
                                }, 600)
                            }else {
                                this.disabled = false
                            }
                        }).catch(()=>{
                            this.disabled = false
                        })
                    }
                })
            },
            changeEmitLabel(data){
                if(data){
                    this.form.categoryName = data;
                }
            },
            reset(){
                this.form = {
                    merchantName:"",
                    productUrl:"",
                    money:"",
                    categoryName:"",
                    categoryId:"",
                    productSource:"",
                    pics:[],
                    id:this.$route.query.id ? this.$route.query.id : null,
                };
                this.$refs.formRef.resetFields();
            }
        }
    }
</script>

<style lang="scss">

</style>